#!/usr/bin/python  
# -*- coding: utf-8 -*-  
#coding=utf-8  
#
#随机买卖脚本
#根据提供的价格，取涨停和跌停之间随机价格，买入或者卖出



import urllib
import urllib2
import random
import time
import threading
import json

mColId = 31
mOpenPrice = 28.02
mUsers = []
mHost = 'http://xjtest.zhugejinfu.com'

mTradeApi = '/trade/entrust'

##
# 获取涨停与跌停之间的随机数，保留两位小数
#
#price 价格
##
def getRandomPrice(price):    
	minPrice = price * 0.9
    	maxPrice = price * 1.1
    	rprice = round(random.uniform(minPrice, maxPrice), 2)
    	print rprice
    	return rprice


##
# 买卖交易
#
#cookie 用户cookie
##
def tradeEntrust(cookie):
	print "执行用户 cookie = " + cookie
	while True:
		tradeType = random.randint(1, 2)
		price = getRandomPrice(mOpenPrice)
		if (tradeType == 1) :
			print "买入 id = " + str(mColId) + ", price = " + str(price)
		else :
			print "卖出 id = " + str(mColId) + ", price = " + str(price)

		params = {"type":tradeType, "col_id":mColId, "count":1, "price":price}
		headers = {"Cookie": "sid=" + cookie}
		data = urllib.urlencode(params)
		req = urllib2.Request(mHost + mTradeApi, data, headers)
		response = urllib2.urlopen(req)
		print response.read()
		time.sleep(5)


##
#获取cookie
#
###

def getCookieById(id) :
	url = mHost + "/test/login?id=%s"%str(id)
	print url
	req = urllib2.Request(url)
	response = urllib2.urlopen(req)
	cookie = response.read()
	print cookie
	return cookie[4:]

##
#设置users
#
#连续用户
##
def setUsersSequence(minId, maxId) :
	x = minId;
	while x <= maxId:
		mUsers.append(x)
		x = x + 1

##
#设置users
#
#不连续用户
###
def setUsers(usersStr) :
	for user in usersStr.split(','):
		mUsers.append(user)		

##
#加载配置信息
#
#
###
def loadConfigs() :
	 with open('config.txt') as json_file:
        	data = json.load(json_file)
		print data
		global mColId
		global mHost
		global mOpenPrice
		mColId = data['col_id']
		mHost = data['host']
		mOpenPrice = data['price']
		if (data['min'] > 0 and data['min'] < data['max']):
			setUsersSequence(data['min'], data['max'])
		else:
			setUsers(data['users'])


loadConfigs()
print mUsers
print '跑脚本的藏品 id = ' + str(mColId) + '价格 price = ' + str(mOpenPrice)
print 'user = ' + str(mUsers)
for user in mUsers:
	cookie = getCookieById(user)
	userThread = threading.Thread(target = tradeEntrust, args = (cookie,))
	userThread.start()





